<?php


namespace app\admin\controller;


use app\libs\Utils;
use app\model\AdminStoreUser;
use app\model\AppWxUser;
use app\util\ReturnCode;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class StoreUser extends Base
{
    public function getByNickName(){
        $nickName = $this->request->param('nickname');
        try {
            $where = $this->addTid([]);
            $result = (new AppWxUser())->where($where)->whereLike('nickname', "%{$nickName}%")->select();
            return $this->buildSuccess($result);
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED,'无数据');
    }
    /**
     * 店铺添加
     */
    public function save()
    {
        $post = $this->request->post();
        $id = $this->request->param('id');
        $post = $this->addTid($post);
        if(Utils::isEmpty($id)){
            $where = $this->addTid(['sid'=>$post['sid'],'unionid'=>$post['unionid']]);
            $model = AdminStoreUser::get($where);
            if($model){
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '此用户已经添加过了，不要重复添加');
            }
            $res = AdminStoreUser::create($post);
        }else{
            unset($post['create_time']);
            unset($post['update_time']);
            $res = AdminStoreUser::update($post);
        }
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }
    /**
     * 删除
     * @return array
     */
    public function del()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $where = ['id'=>$id];
        $where = $this->addTid($where);
        AdminStoreUser::destroy($where);
        return $this->buildSuccess([]);
    }

    /**
     * 获取列表
     * @return array
     * @throws \think\exception\DbException
     * @author chniccs
     */
    public function getList()
    {

        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $sid = $this->request->get('sid');
        if(!isset($sid)){
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $obj = new AdminStoreUser();
        $where = ['sid'=>$sid];
        $where = $this->addTid($where);
        $listObj = $obj->order('create_time DESC')->where($where)->paginate($limit, false, ['page' => $start])->toArray();
        return $this->buildSuccess([
            'list' => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }
}